package bit.project.services.impl;

import bit.project.common.AppResult;
import bit.project.common.ResultCode;
import bit.project.dao.UserMapper;
import bit.project.exception.ApplicationException;
import bit.project.model.User;
import bit.project.services.IUserService;
import bit.project.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class UserService implements IUserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public User selectByUserName ( String username){
        //非空校验
        if(StringUtils.isEmpty(username)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO查询
        User user = userMapper.selectByUserName(username);
        return user;
    }

    @Override
    public void createNormalUser(User user) {
        //非空校验
        if(user == null || StringUtils.isEmpty(user.getUsername())
        ||StringUtils.isEmpty(user.getNickname())||StringUtils.isEmpty(user.getPassword())
        ||StringUtils.isEmpty(user.getSalt())){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验用户是否存在
        User user1 = selectByUserName(user.getUsername());
        if(user1!=null){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        //设置默认值
        if(user.getGender()==null||user.getGender()<0||user.getGender()>2){
            //性别保密
            user.setGender((byte) 2);
        }
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setDeleteState((byte) 0);
        user.setState((byte) 0);
        Date data = new Date();
        user.setCreateTime(data);
        user.setUpdateTime(data);
        //写入用户数据，返回结果
        int row = userMapper.insert(user);
        if(row!=1){
            log.warn("用户注册，"+ ResultCode.FAILED_CREATE);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
    }
}
